<?php
/**
 * Created by PhpStorm.
 * User: khq
 * Date: 16-12-29
 * Time: 下午3:08
 */
namespace Inbound\Service;

use Home\Service\CommonService;
use Inbound\Model\PrepareneedsdetailModel;
use Inbound\Model\PrepareneedsModel;
use Warehouse\Model\StockInModel;
use Think\Exception;
use Inbound\Model\SkusiterelationModel;
class PrepareneedsService extends CommonService
{

    public $prepareneeds              = NULL;

    public $prepareneedsdetail        = NULL;

    public $prepareneedsdetailsshipmentid = NULL;

    public $AccountSellerSku = NULL;

    public $stockInModel = NULL;

    //查询记录总数
    public $count           = 0;
    //页面展示包含页面样式
    public $page            = 0;
    //数据
    public $data            = array();
    //当前时间
    public $time            = NULL;

    /*
     * 构造函数初始化
     * */
    public function __construct($table = '',$param=array())
    {
        $this->prepareneeds = D('Inbound/prepareneeds','Model');
        //实例化需求备货对象
        $this->prepareneedsdetail = D('Inbound/prepareneedsdetail','Model');
        $this->AccountSellerSku = D('Api/Amazon/AccountSellerSku','Service');
        $this->prepareneedsdetailsshipmentid = D('Inbound/prepareneedsdetailsshipmentid', 'Model');
        $this->time         = date('Y-m-d H:i:s',time());
        $this->stockInModel = D('Warehouse/StockIn', 'Model');
    }

    public function create($_array = array(),&$model = NULL)
    {
    }

    public function update($_array = array(),$_param= array(),&$model = NULL)
    {

    }
    public function judge_is_change()
    {

    }
    public function delete()
    {
    }

    /**
     * @param $code_info
     * @return array|int
     * 根据需要切换批次的信息获取或以切换的批次号
     */
    public function getCodeInfo($code_info)
    {
        $input_batch_codes = array();

        foreach ($code_info as $info) {
            $input_batch_codes[] = $info['batch_code'];
            $result = $this->prepareneedsdetail->batchCodeSelect($info);
            /*如果在结果存在，则说明要切换批次号的SKU在别的批次号里有相同的SKU、帐号名称、要求到货时间
             *则这次切换批次号操作不允许
             */
            if ($result) {
                $needIsReplyInOtherBatchCode = 1;
                return $needIsReplyInOtherBatchCode;
            }
        }

        $batch_codes = $this->prepareneedsdetail->canChangeCodeSelect();

        /*把状态为10的批次号中包含的需要切换的批次号去重*/
        if (is_array($batch_codes)) {
            $batch_codes = array_diff($batch_codes, $input_batch_codes);
        }

        return $batch_codes;
    }

    /**
     * @param $code_info
     * @return int
     * 根据ID更新批次号
     */
    public function updateCode($code_info)
    {
        $ids = array();
        $org_code = array();
        foreach ($code_info['code_info'] as $code) {
            $ids[] = $code['id'];
            $org_code[] = $code['batch_code'];
        }

        $result = $this->prepareneedsdetail->batchCodeUpdate($ids, $org_code, $code_info['target_code']);

        return $result ? $result : 0;
    }

    /**
     * @param $sku
     * @return int
     * 描述：通过SKU获得可用库存
     */
    public function skuInventoryGet($sku) {
        $inventory = $this->stockInModel->get_storage_inventories('', $sku);

        $sku = $inventory->select();

        return $sku['all_available_quantity'] ? $sku['all_available_quantity'] : 0;
    }

    /**
     * @param $stockingDetail
     * @return bool
     * 描述：传入备货需求ID和是否单独发货状态更新备货需求
     */
    public function logisticsPreview($stockingDetail) {
        $result = $this->prepareneedsdetail->logisticsPreview($stockingDetail);

        if ($result === count($stockingDetail)) {
            return true;
        } else {
            return false;
        }
    }

    public function compliancePreview($complianceData) {
        $result = $this->prepareneedsdetail->compliancePreview($complianceData);

        if ($result === count($complianceData)) {
            return true;
        } else {
            return false;
        }
    }

    public function download_compliance() {
        $complianceArr = PublicInfoService::get_compliance_array();

        $condition = array();
        foreach ($_GET as $key => $value) {
            switch($key) {
                case 'sku' :
                    $condition['fpnd.sku'] = $value;
                    break;
                case 'site_id' :
                    $condition['fpnd.site_id'] = $value;
                    break;
                case 'compliance_check_time_from' :
                    $condition['fpnd.compliance_check_time'][] = array('EGT', $value);
                    break;
                case 'compliance_check_time_to' :
                    $condition['fpnd.compliance_check_time'][] = array('ELT', $value);
                    break;
            }
        }

        $condition['fpnd.compliance_check_time'][] = array('EXP', 'IS NOT NULL');
        $condition['fpnd.compliance_check_user_id'] = array('EXP', 'IS NOT NULL');

        $data = $this->prepareneedsdetail->getComplianceInfo($condition);

        foreach ($data as &$compliance_info) {
            $compliance_str = '';
            $compliance = explode(',', $compliance_info['compliance']);
            foreach ($compliance as $val) {
                $compliance_str .= $complianceArr[$val] . "，";
            }
            $compliance_info['compliance'] = trim($compliance_str,'，');
        }

        $firstLine = array(
            "compliance_check_time" => "日期",
            "sku" => "SKU",
            "name" => "SKU中文名称",
            "shorthand_code" => "站点",
            "remark" => "采购跟单",
            "compliance" => "审核异常",
            "comment" => "审核备注");

        $fileName = "合规审核信息报表";

        $this->download_function($data, $firstLine, $fileName);
    }

    /**
     * @param $checkArray
     * @return bool
     * 描述：检验输入的备货申请是否重复
     */
    public function checkRepeat($checkArray) {
        $strArray = array();

        foreach ($checkArray as $array) {
            $str = '';
            $str .= $array['sku'] . ',';
            $str .= $array['seller_sku'] . ',';
            $str .= $array['export_tax_rebate'] . ',';
            $str .= $array['enterprise_dominant'] . ',';
            $str .= $array['claim_arrive_time'];

            $strArray[] = $str;
        }

        $uniqueArray = array_unique($strArray);
        return (count($strArray) > count($uniqueArray)) ? true : false;
    }

    /**
     * @param $stockingApplyData
     */
    public function stockingApplyInsert($stockingApplyData) {
        $resultArray = array();
        $tranResult = true;

        if ($this->checkRepeat($stockingApplyData)) {
            $resultArray['status'] = 0;
            $resultArray['message'] = "备货需求重复！";
            return $resultArray;
        }

        try{
            $result = $this->prepareneedsdetail->batch_create($stockingApplyData);

            if ($result === false) {
                throw new Exception("数据提交失败！");
            }
        } catch (Exception $e) {
            $tranResult = false;
            $resultArray['message'] = $e->getMessage();
        }

        if ($tranResult === false) {
            $this->prepareneedsdetail->model->rollback();
            $resultArray['status'] = 0;
        } else {
            $this->prepareneedsdetail->model->commit();
            $resultArray['message'] = "数据提交成功！";
            $resultArray['status'] = 1;
        }

        return $resultArray;

    }

    /*
     *计划单抓取  获取批次号
     */
    public function select_batch_code(){
        return $this->prepareneeds->prepare_needs->field('id,batch_code')->order('create_time desc')->select();
    }
    /**
     * 获取备货需求数据
     * 参数 数组(查询条件) 控制器类
     * 返回 备货需求单详情
     */
    public function get_prepareneeds_data(&$_array = array(),$flag = TRUE)
    {
        $prepareneeds        = $this->get_prepareneeds_model($_array);
        $prepareneeds_count = clone $prepareneeds;

        if($flag)
        {
            $this->count= $prepareneeds_count->count();      //数量

            $Page = new \Org\Util\Page($this->count,20);     //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();// 分页显示输出

            $prepareneeds->order("create_time desc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $prepareneeds->select();
        $result = $this->format_prepareneeds_data($result);
        return $result;
    }

    /**
     * @param $data
     * @return mixed
     * 格式化备货需求数据
     */
    public function format_prepareneeds_data($data)
    {
        //格式化
        $status_arr   = PublicInfoService::get_prepareneeds_status_array();
        $transfer_arr = D('TransferHopperAddress','Service')->getTransferHopperAddress(); //中转仓信息数组
        foreach($data as &$_data)
        {
            $_data['create_user_id']  = PublicInfoService::get_user_name_by_id($_data['create_user_id']);
            $_data['status']      = $status_arr[$_data['status']];
            $_data['transfer_hopper_id'] = $transfer_arr[$_data['transfer_hopper_id']]['name'];
        }
        return $data;
    }
    /**
     * 获得备货需求model对象
     * 参数 查询条件
     * 返回 对象
     */
    public function get_prepareneeds_model($_array)
    {
        $prepareneeds = M(PrepareneedsModel::$table,' ',$this->prepareneeds->_db);

        if($_array)
            $_array = array_filter($_array);
        $_array = $this->trim_array($_array);

        foreach($_array as $key=>$_arr) {
            switch($key){
                case 'create_time_from':
                    $_array['create_time'][] = array('egt',$_arr);
                    unset($_array['create_time_from']);
                    break;
                case 'create_time_to':
                    $_array['create_time'][] = array('elt',$_arr);
                    unset($_array['create_time_to']);
                    break;
            }
        }
        return $prepareneeds -> where($_array);
    }

    /**
     * @param array $_array
     * @param bool $flag
     * @return mixed
     * 查询备货需求明细
     */
    public function select_detail($_array = array(),$flag = TRUE)
    {
        $prepareneedsdetail   = $this->get_prepareneeds_detail_model($_array);

        $prepareneedsdetail_count = clone $prepareneedsdetail;

        if($flag)
        {
            $this->count= $prepareneedsdetail_count->count();      //数量

            $Page = new \Org\Util\Page($this->count,50);           //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();                           // 分页显示输出

            $prepareneedsdetail

                ->order("fpnd.sku")
                ->field("fpnd.*,log.logic_attr,fpnsc.compliance,fpnsc.comment")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $prepareneedsdetail->field("fpnd.*,log.logic_attr,fpnsc.compliance,fpnsc.comment")->select();

        $result = $this->format_prepareneeds_detail_data($result);
        return $result;
    }
    /**
     * @version 查询备货需求明细
     * @param array $_array
     * @param bool $flag
     * @return mixed
     */
    public function select_detail_other($_array = array(),$flag = TRUE)
    {
        $prepareneedsdetail   = $this->get_prepareneeds_detail_model_other($_array);
        $prepareneedsdetail_count = clone $prepareneedsdetail;

        if($flag)
        {
            $this->count= $prepareneedsdetail_count->count();      //数量

            $Page = new \Org\Util\Page($this->count,50);           //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();                           // 分页显示输出

            $prepareneedsdetail->order("sku")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $prepareneedsdetail->select();
        $result = $this->format_prepareneeds_detail_data_other($result);
        return $result;
    }
    /**
     * @param array $_array
     * @param bool $flag
     * @return mixed
     * 查询单个备货需求明细
     */
    public function select_single_detail($_array = array(),$flag = TRUE)
    {
        $prepareneedsdetail   = $this->get_prepareneeds_detail_model($_array);
        $prepareneedsdetail_count = clone $prepareneedsdetail;

        if($flag)
        {
            $this->count= $prepareneedsdetail_count->count();      //数量

            $Page = new \Org\Util\Page($this->count,20);           //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();                           // 分页显示输出

            $prepareneedsdetail->order("account_id,site_id,export_tax_rebate,carrier_service_id,claim_arrive_time")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $map['status'] = array('neq',100);                         //取消的明细不导出
        $map['needs_quantity'] = array('neq',0);                   //需求数量为0的不导出
        $result = $prepareneedsdetail
            ->where($map)
            ->select();
        $result = $this->format_prepareneeds_detail_data($result);
        return $result;
    }

    /**
     * @param array $_array
     * @return mixed
     * ajax获取特殊格式单条明细
     * khq 2017.1.12
     */
    public function ajax_select_detail($_array = array())
    {
        $prepareneedsdetail   = $this->get_prepareneeds_detail_model($_array);

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result       = $prepareneedsdetail->find();
        //$main_datas   = $this->prepareneeds->get_data_by_code($result['batch_code']);
        $site_arr     = PublicInfoService::get_site_array();
        $status_arr   = PublicInfoService::get_prepareneeds_status_array();
        $data = PublicInfoService::getOverseasSupervision($result['sku'], $result['site_id']);
        $result['overseas_supervision']= $data['overseas_supervision'];
        $result['cargo_grade']= $data['cargo_grade'];
        $result['site']=$result['site_id'];
        $result['site_id']     = $site_arr[$result['site_id']];
        $result['status_name']      = $status_arr[$result['status']];
        //$result['main_status'] = $main_datas['status'];                              //备货需求主表状态
        return $result;
    }

    public function download_function($data, $firstLine, $fileName) {
        set_time_limit(0);
        ini_set('memory_limit','2048M');

        $output = fopen('php://output', 'w') or die("can't open php://output");
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$fileName.(" .date("Ymd").").csv");
        ob_end_clean();

        fputcsv($output, array_values($firstLine));
        foreach ($data as $_data) {
            $_output = array();
            foreach ($firstLine as $key => $val) {
                $_output[$key] = $_data[$key];
            }
            fputcsv($output, array_values($_output));
        }

        fclose($output) or die("can't close php://output");
        exit;

    }

    /**
     * @param $detail_data
     * 导出预捡储位导入时需要的明细
     * khq 2017.1.4
     */
    public function download_detail_typeone(&$detail_data){

        set_time_limit(0);
        ini_set('memory_limit','2048M');

        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $fileName = $detail_data[0]['batch_code']."批次备货需求明细(".date('Ymd',time()).")";

        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$fileName.csv");
        //输出表头
        $table_head = array(
            '批次号','sku','账号','站点','虚拟sku', 'sku名称', '需求数量', '储位', '预拣数量',
            '是否退税','销售员','采购员','要求到货时间'
        );
        fputcsv($output, $table_head);
        //输出每一行数据到文件中
        foreach ($detail_data as $info) {
            $data_arr = array(
                'batch_code'        => $info['batch_code'],
                'sku'               => $info['sku'],
                'account_name'      => $info['account_name'],
                'site_id'           => $info['site_id'],
                'sku_virtual'       => $info['sku_virtual'],
                'sku_name'          => $info['sku_name'],
                'needs_quantity'    => $info['needs_quantity'],
                'storage'           => $info['storage'],
                'actual_quanlity'   => $info['actual_quanlity'],
                'export_tax_rebate' => $info['export_tax_rebate'],
                'seller_id'         => $info['seller_id'],
                'buyer_id'          => $info['buyer_id'],
                'claim_arrive_time' => $info['claim_arrive_time']
            );
            fputcsv($output, array_values($data_arr));
            unset($data_arr);
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }
    public function download_detail(&$detail_data){

        set_time_limit(0);
        ini_set('memory_limit','2048M');

        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $fileName = $detail_data[0]['batch_code']."备货需求详情(".date('Ymd',time()).")";

        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$fileName.csv");
        //输出表头
        $table_head = array(
            '账号名称','sku','sellerSKU', 'sku名称','站点', '需求数量',
            '是否出口退税', '公司主体','SKU报关编码',' SKU申报要素','SKU品名','单据创建人','单据生成时间',
            '状态','销售员','采购员','备注','要求到货时间','销售确认人',
            '销售确认时间','合规预审时间','合规预审人','物流预审人','物流预审时间','物流属性'
        );
        fputcsv($output, $table_head);
        //输出每一行数据到文件中
        foreach ($detail_data as $info) {
            unset($info['id']);
            unset($info['prepare_needs_id']);
            unset($info['account_id']);
            unset($info['batch_code']);
            unset($info['sku_virtual']);
            unset($info['transfer_hopper_id']);
            unset($info['storage']);
            unset($info['actual_quanlity']);
            unset($info['carrier_service_id']);
            unset($info['single_ship']);
            unset($info['compliance']);
            unset($info['stocker_check_user_id']);
            unset($info['stocker_check_time']);
            unset($info['carrier_choose_user_id']);
            unset($info['carrier_choose_time']);
            unset($info['over_user_id']);
            unset($info['over_time']);
            unset($info['cargo_grade']);
            unset($info['comment']);

            fputcsv($output, array_values($info));
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }
    public function download_detail_other(&$detail_data){
        set_time_limit(0);
        ini_set('memory_limit','2048M');
        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $fileName = "FBA备货需求计划单";
        $limit = 1000;
        $calc  = 0;
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$fileName.csv");
        //输出表头
        $table_head = array(
            '账号名称','站点','sellerSKU', 'SKU','采购订单号','采购员','采购名称','报关品名','英文品名','海关编码','退税率','品牌','型号','申报要素',
            '净重KG(单个SKU)','毛重KG（GW/PCS,包装后的单个SKU）','体积CM3（包装后的单个SKU体积）','需求数量','含税采购单价','含税采购总额',
            '是否出口退税','采购主体','要求到货时间','销售员','是否单独发货','状态','物流渠道（备注）','备货需求创建人','备货需求创建时间','销售确认人',
            '销售确认时间','合规组审核人','合规组审核时间','物流预审人','物流预审时间'
        );
        foreach($table_head as $v){
            $tit[] = iconv('UTF-8','GB2312//IGNORE',$v);
        }
        fputcsv($output, $tit);
        //输出每一行数据到文件中
        foreach ($detail_data as $info) {
            $down=array(
                $info['account_name'],
                $info['site_id'],
                $info['seller_sku'],
                $info['sku'],
                $info['purchaseorder_id'],
                $info['purchase_id'],
                $info['sku_name'],
                $info['sku_cname'],
                $info['en_item'],
                $info['hs_code'],
                $info['export_tax'],
                $info['logo'],
                $info['type_number'],
                $info['declaration_element'],
                $info['weight'],//净重
                $info['asweight'],//毛重
                $info['volume'],
                $info['needs_quantity'],
                $info['single_price'],
                $info['money'],
                $info['export_tax_rebate'],
                $info['enterprise_dominant_other'],
                $info['claim_arrive_time'],
                $info['seller_id'],
                $info['single_ship'],
                $info['status'],
                $info['carrier_service_id'],
                $info['create_user_id'],
                $info['create_time'],
                $info['seller_check_user_id'],
                $info['seller_check_time'],
                $info['compliance_check_user_id'],
                $info['compliance_check_time'],
                $info['logistic_check_user_id'],
                $info['logistic_check_time'],
            );
            $calc++;
            if($limit==$calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($down as $t){
                $tarr[] = iconv('UTF-8','GB2312//IGNORE',trim($t));
            }
            fputcsv($output,$tarr);
            unset($tarr);
        }
        unset($detail_data);
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }
    /**
     * @param $data
     * @return mixed
     * 格式化备货需求明细数据
     * khq
     */
    public function format_prepareneeds_detail_data($data)
    {
        $company_arr       = PublicInfoService::get_company_array();
        $status_arr        = PublicInfoService::get_prepareneeds_status_array();
        $site_arr          = PublicInfoService::get_site_array();
        $transport_way_arr = PublicInfoService::get_transport_way_array();
        $logic_arr         = PublicInfoService::get_sku_logic_name_array();
        $comliance_arr     = PublicInfoService::get_compliance_array();

        //特殊账号行用红色标志
        $specialConfig = C('compliance');

        //格式化
        foreach($data as &$_data) {
            if(!empty($specialConfig) && in_array($_data['account_id'], $specialConfig))
                $_data['complianceSpecial'] = 1;
            else
                $_data['complianceSpecial'] = 0;
            $_data['seller_id']             = PublicInfoService::get_user_name_by_id($_data['seller_id']);
            $_data['buyer_id']              = PublicInfoService::get_user_name_by_id($_data['buyer_id']);
            $_data['site_id']               = $site_arr[$_data['site_id']];
            $_data['carrier_service_id']    = $transport_way_arr[$_data['carrier_service_id']];
            $_data['create_user_id']        =
                PublicInfoService::get_user_name_by_id($_data['create_user_id']);   //创建人
            $_data['seller_check_user_id']  =
                PublicInfoService::get_user_name_by_id($_data['seller_check_user_id']);         //销售确认
            $_data['compliance_check_user_id']  =
                PublicInfoService::get_user_name_by_id($_data['compliance_check_user_id']);
            $_data['logistic_check_user_id']=
                PublicInfoService::get_user_name_by_id($_data['logistic_check_user_id']);       //物流预审确认
            $_data['export_tax_rebate']     = $_data['export_tax_rebate']==1?'是':'否';
            $_data['enterprise_dominant']   = $company_arr[$_data['enterprise_dominant']];

            $com_str = '';
            if ($_data['status'] == 15) {
                foreach ($comliance_arr as $key => $arr) {
                    $com_str .= '<label for="' . $_data['id'] . '_' . $key . '">
                        <input class="com_opt" type="checkbox" id="' . $_data['id'] . '_' . $key .'" value="' . $key . '"';
                    if ($_data['compliance']) {

                        $com_arr = explode(',', $_data['compliance']);
                        if (in_array($key, $com_arr)) $com_str .= ' checked="checked"';
                    }

                    $com_str .= '">' . $arr . '</label>';
                }
                $com_str .= '<input class="com_comment" style="width:100px" placeholder="请输入备注" type="text" value="' . $_data['comment'] . '" >';
                $_data['compliance'] = $com_str;
            } else {
                if ($_data['compliance']) {
                    $com_arr = explode(',', $_data['compliance']);
                    foreach ($com_arr as $val) {
                        $com_str .= "<b>" . $comliance_arr[$val] . "</b>,<br/>";
                    }
                    $com_str .= $_data['comment'] ? '<b>备注:</b>' . $_data['comment'] : '';
                    $_data['compliance'] = $com_str;
                }
            }

            $_data['statusId']              = $_data['status'];
            $_data['status']                = $status_arr[$_data['statusId']];
            $_data['logic_attr']            = $logic_arr[$_data['logic_attr']];
            //$_data['single_ship']           = $_data['single_ship'] == 1 ? '是' : '否';
        }
        return $data;
    }
    /**
     * @version 格式化备货需求明细数据
     * @param $data
     * @return mixed
     */
    public function format_prepareneeds_detail_data_other($data)
    {
        $company_arr       = PublicInfoService::get_company_array();
        $status_arr        = PublicInfoService::get_prepareneeds_status_array();
        $site_arr          = PublicInfoService::get_site_array();
        $transport_way_arr = PublicInfoService::get_transport_way_array();
//        $result=PublicInfoService::getPurchase(460835102);
//        print_r($result);
//        exit;
        //格式化
        foreach($data as &$_data)
        {
            $_data['seller_id']             = PublicInfoService::get_user_name_by_id($_data['seller_id']);
            $_data['buyer_id']              = PublicInfoService::get_user_name_by_id($_data['buyer_id']);
            $_data['site_id']               = $site_arr[$_data['site_id']];
            $_data['carrier_service_id']    = $transport_way_arr[$_data['carrier_service_id']];
            $_data['create_user_id']        =PublicInfoService::get_user_name_by_id($_data['create_user_id']);   //创建人
            $_data['seller_check_user_id']  =PublicInfoService::get_user_name_by_id($_data['seller_check_user_id']);         //销售确认
            $_data['compliance_check_user_id'] = PublicInfoService::get_user_name_by_id($_data['compliance_check_user_id']);
            $_data['logistic_check_user_id']=PublicInfoService::get_user_name_by_id($_data['logistic_check_user_id']);       //物流预审确认
            $_data['export_tax_rebate']     = $_data['export_tax_rebate']==1?'是':'否';
            $_data['enterprise_dominant']   = $company_arr[$_data['enterprise_dominant']];
            $_data['status']                = $status_arr[$_data['status']];
            $_data['single_ship']           = $_data['single_ship'] == 1 ? '是' : '否';
            //采购单信息
            $purchaseArr=PublicInfoService::getPurchase($_data['purchaseorder_id']);
            if(!empty($purchaseArr)){
                $_data['purchase_id']=PublicInfoService::get_user_name_by_id($purchaseArr['purchase_id']);
                $_data['enterprise_dominant_other']=$company_arr[$_data['enterprise_dominant_other']];
            }else{
                $_data['purchase_id']='';
                 $_data['enterprise_dominant_other']='';
            }
            //品牌
            $_data['logo']=PublicInfoService::getLogo($_data['sku']);
            //型号
            $_data['type_number']=PublicInfoService::getTypeNumber($_data['sku']);
            //英文品名
            $_data['en_item']=PublicInfoService::getEnItem($_data['sku']);
            //净重
            $_data['weight']=PublicInfoService::getWeight($_data['sku']);
            //毛重
            $_data['asweight']=PublicInfoService::getAsWeight($_data['sku']);
            //体积
            $_data['volume']=PublicInfoService::getVolume($_data['sku']);
        }
        return $data;
    }

    public function occupiedStockingNeedInventoryGet($array) {
        $company = PublicInfoService::get_company_array();
        $status = PublicInfoService::get_prepareneeds_status_array();
        $result = array();

        if (isset($array['shipmentid'])) return $result;

        $array['status'] = array('IN', '10,15,20,30');
        $column = array('sku', 'sku_name', 'needs_quantity AS quantity', 'export_tax_rebate', 'enterprise_dominant', 'status',
            'account_name', 'seller_id');
        $prepareneedsdetail = M(PrepareneedsdetailModel::$table,' ',$this->prepareneedsdetail->_db);

        $result = $prepareneedsdetail->field($column)->where($array)->select();

        if (!empty($result)) {
            foreach ($result as &$data) {
                $data['export_tax_rebate'] = $data['export_tax_rebate'] == 1 ? '是' : '否';
                $data['enterprise_dominant'] = $company[$data['enterprise_dominant']];
                $data['status'] = $status[$data['status']];
                $data['shipmentid'] = '';
                $data['seller']  = PublicInfoService::get_user_name_by_id($data['seller_id']);
            }

        }

        return $result;

    }

    /**
     * 获得备货需求明细model对象
     * 参数 查询条件
     * 返回 对象
     */
    public function get_prepareneeds_detail_model(&$_array)
    {   $array = array();
        foreach ($_array as $key => $value) {
            if ($key == 'p') continue;
            $array['fpnd.' . $key] = $value;

        }

        $prepareneedsdetail = M(PrepareneedsdetailModel::$table,' ',$this->prepareneedsdetail->_db);

        $prepareneedsdetail->table('fba_prepare_needs_details fpnd')
            ->join('LEFT JOIN skusystem_sku_logic log on fpnd.sku = log.sku AND log.isavailable = 1 ')
            ->join('LEFT JOIN fba_prepare_needs_sku_compliance fpnsc on fpnsc.site_id = fpnd.site_id AND fpnsc.sku = fpnd.sku');
        if($array){
            $flag = false;
            if($array['fpnd.export_tax_rebate']==='0') $flag=true;                             //非退税设为0的后果,多三行代码
            if (trim($array['fpnd.create_user_id'])) $array['fpnd.create_user_id'] =
                PublicInfoService::get_user_id_by_name($array['fpnd.create_user_id']);
            $array = array_filter($array);
            if($flag) $array['fpnd.export_tax_rebate'] = 0;
        }
        $array = $this->trim_array($array);

        foreach($array as $key=>$_arr) {
            switch($key){
                case 'fpnd.create_time_from':
                    $array['fpnd.create_time'][] = array('egt',$_arr);
                    unset($array['fpnd.create_time_from']);
                    break;
                case 'fpnd.create_time_to':
                    $array['fpnd.create_time'][] = array('elt',$_arr);
                    unset($array['fpnd.create_time_to']);
                    break;
                case 'fpnd.claim_arrive_time_from':
                    $array['fpnd.claim_arrive_time'][] = array('egt',$_arr);
                    unset($array['fpnd.claim_arrive_time_from']);
                    break;
                case 'fpnd.claim_arrive_time_to':
                    $array['fpnd.claim_arrive_time'][] = array('elt',$_arr);
                    unset($array['fpnd.claim_arrive_time_to']);
                    break;
                case 'fpnd.compliance_check_time_from' :
                    $array['fpnd.compliance_check_time'][] = array('EGT', $_arr);
                    unset($array['fpnd.compliance_check_time_from']);
                    break;
                case 'fpnd.compliance_check_time_to' :
                    $array['fpnd.compliance_check_time'][] = array('ELT', $_arr);
                    unset($array['fpnd.compliance_check_time_to']);
                    break;
            }
        }
        return $prepareneedsdetail->where($array);
    }
    /**
     * @version 获得备货需求明细model对象
     * @param array $_array 查询条件
     * return  对象
     */
    public function get_prepareneeds_detail_model_other(&$_array)
    {
        $prepareneedsdetail = M(PrepareneedsdetailModel::$table,' ',$this->prepareneedsdetail->_db)
            ->table($this->prepareneedsdetail->_db . '.fba_prepare_needs_details AS fispd')
            ->join('LEFT JOIN wms_purchaseorder_details wpd on wpd.sku = fispd.sku')
            ->field("fispd.*,wpd.purchaseorder_id,wpd.export_tax,wpd.single_price,wpd.money");
        if($_array){
            $flag = false;
            if($_array['export_tax_rebate']==='0') $flag=true;                             //非退税设为0的后果,多三行代码
            if (trim($_array['create_user_id'])) 
                $_array['create_user_id'] =PublicInfoService::get_user_id_by_name($_array['create_user_id']);
            $_array = array_filter($_array);
            if($flag) $_array['export_tax_rebate'] = 0;
        }
        $_array = $this->trim_array($_array);
        if (!empty($_array['status'])) {
            $_array['fispd.status'] = array('eq', $_array['status']);
            unset($_array['status']);
        }
        if (!empty($_array['sku'])) {
            $_array['fispd.sku'] = array('eq', $_array['sku']);
            unset($_array['sku']);
        }
//        print_r($_array);
//        exit;
        foreach($_array as $key=>$_arr) {
            switch($key){
                case 'create_time_from':
                    $_array['create_time'][] = array('egt',$_arr);
                    unset($_array['create_time_from']);
                    break;
                case 'create_time_to':
                    $_array['create_time'][] = array('elt',$_arr);
                    unset($_array['create_time_to']);
                    break;
                case 'claim_arrive_time_from':
                    $_array['claim_arrive_time'][] = array('egt',$_arr);
                    unset($_array['claim_arrive_time_from']);
                    break;
                case 'claim_arrive_time_to':
                    $_array['claim_arrive_time'][] = array('elt',$_arr);
                    unset($_array['claim_arrive_time_to']);
                    break;
            }
        }
//        print_r($_array);
        return $prepareneedsdetail -> where($_array);
    }

    /**
     * @param $arr
     * @return array|string
     * 过滤数组中元素的空格
     * khq 2017.1.20
     */
    public static function trim_array($arr) {
        if (!is_array($arr)) {
            return trim($arr);
        }
        try {
            while (list($key, $value) = each($arr)) {
                if (is_array($value)) {
                    self::trim_array($value);
                } else {
                    $arr[$key] = trim($value);
                }
            }
        }catch (Exception $e){
            echo $e->getMessage();
        }
        return $arr;
    }

    /**
     * @param $arr -导入文件数组
     * @return string
     * khq 2016.12.30
     */
    public function upload_platform($arr)
    {

        $batch_code = $this->create_batch_code();                                           //创建需求批次号
        if(!$batch_code) return array('status'=>401);
        $batch_data = array(
            'batch_code'     => $batch_code,
            'remark'         => '批量导入创建',
            'status'         => 10,
            'create_user_id' => $_SESSION['current_account']['id'],
            'transfer_hopper_id' => $_POST['transfer_hopper_id'],
            'create_time'    => $this->time
        );

        $this->prepareneeds->create($batch_data);                                           //备货需求表
        if($this->prepareneeds->prepare_needs_id)
        {
            try{
                $datas = $this->upload_platform_detail($arr,
                    $this->prepareneeds->prepare_needs_id,$batch_code);
                $check_result = $this->check_upload_resolve_data($datas);                   //检查解析最终数据的纯洁性
                if($check_result['flag']==false){                                           //导入的数据在系统不存在
                    return array(
                        'status' => 404,
                        'message'=> $check_result['message']
                    );
                }
                $this->prepareneedsdetail->batch_create($datas);                             //创建备货需求明细表
                $this->prepareneeds->model->commit();
                return array('status'=>200);
            }catch (Exception $e)
            {
                $this->prepareneeds->model->rollback();
                print $e->getMessage();
                return array('status'=>403);
            }
        }else{
            $this->prepareneeds->model->rollback();
            return array('status'=>402);
        }
    }

    /**
     * @param $arr
     * @return array
     * 导入储位和预捡数量
     * khq 2017.1.11
     */
    public function upload_create_storage($arr)
    {
        try{
            $datas = $this->upload_create_storage_detail($arr);                         //获取数据
            $check_result = $this->check_create_storage_resolve_data($datas);           //检查解析最终数据的纯洁性
            if($check_result['flag']==false){                                           //导入的数据在系统不存在
                return array(
                    'status' => 40,
                    'message'=> $check_result['message']
                );
            }
            return $this->update_storage($datas);                                       //更新储位和预捡数量
        }catch (Exception $e)
        {
            print $e->getMessage();
        }
    }

    /**
     * @param $datas
     * @return string
     * 更新储位和预捡数量
     */
    public function update_storage(&$datas)
    {
        $str = '';
        $i = 0;
        foreach ($datas as $k=>$v){
            $map = array(
                'batch_code'        => $v['batch_code'],
                'sku'               => $v['sku'],
                'account_id'        => $v['account_id'],
                'site_id'           => $v['site_id'],
                'export_tax_rebate' => $v['export_tax_rebate'],
                'claim_arrive_time' => $v['claim_arrive_time']
            );
            $id = $this->prepareneedsdetail->get_prepare_detail_id($map);
            if($id){
                $_param = array(
                    'storage'         => $v['storage'],
                    'actual_quanlity' => $v['actual_quanlity']
                );
                $_param['status'] = array('neq',100);                                   //取消的订单不更新
                $this->prepareneedsdetail->update(array('id'=>$id),$_param);
                $this->prepareneedsdetail->model->commit();
            }else{
                $i++;
                $str .= '第'.($k+2).'行数据异常,导入失败</br>';
            }
        }
        $str .= '成功更新'.(count($datas)-$i).'条,失败'.$i.'条';
        return $str;
    }
    /**
     * @param $datas
     * @return array
     * 检查导入的预捡数量解析后的数据
     */
    public function check_create_storage_resolve_data(&$datas)
    {
        $flag = true;
        $str  = '';
        foreach ($datas as $k=>$v){
            if($v['account_id']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 账号 不存在,导入失败</br>';
            }
            if($v['site_id']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 站点 不存在,导入失败</br>';
            }
        }
        return array(
            'flag'     => $flag,
            'message'  => $str
        );
    }

    /**
     * @param $arr
     * @return array
     * 获取导入的预捡数量和储位
     * khq 2017.1.12
     */
    public function upload_create_storage_detail(&$arr)
    {
        $datas = array();
        foreach ($arr as $k=>$v){
            if($k>=2){
                $v = $this->trim_array($v);                                                   //过滤元素的空格
                $data = array(
                    'batch_code'           => mysql_escape_string($v['A']),
                    'sku'                  => mysql_escape_string($v['B']),                   //sku
                    'account_id'           => PublicInfoService::get_account_id(trim($v['C'])),//账号id
                    'site_id'              => PublicInfoService::get_site_id(trim($v['D'])),  //站点
                    'storage'              => trim($v['H']),                                  //储位
                    'actual_quanlity'      => intval($v['I']),                                //实际预捡数量
                    'export_tax_rebate'    => mysql_escape_string($v['J'])=='是'?1:0,         //是否出口退税
                    'claim_arrive_time'    => date('Y-m-d',strtotime(trim($v['M']))),         //要求到货时间
                );
                $datas[] = $data;
            }
        }
        return $datas;
    }

    /**
     * @param $arr
     * @param $needs_id
     * @param $batch_code
     * @return array
     * 上传备货需求明细
     * khq 2016.12.31
     */
    public function upload_platform_detail(&$arr,$needs_id,$batch_code)
    {
        $datas = array();
        foreach ($arr as $K=>$v)
        {
            if($K>=2){
                $v    = $this->trim_array($v);                                                //过滤空格
                $data = array(
                    'sku'                  => strtoupper(mysql_escape_string($v['A'])),
                    'account_name'         => mysql_escape_string($v['B']),                   //平台账号
                    'account_id'           => PublicInfoService::get_account_id(trim($v['B'])),//账号id
                    'site_id'              => PublicInfoService::get_site_id(trim($v['C'])),  //站点
                    'sku_virtual'          => trim($v['D']),                                  //虚拟SKU
                    'sku_name'             => mysql_escape_string($v['E']),                   //sku名称
                    'needs_quantity'       => intval($v['F']),                                //需求数量
                    'export_tax_rebate'    => mysql_escape_string($v['I'])=='是'?1:0,         //是否出口退税
                    'enterprise_dominant'  => PublicInfoService::getCompanyId(trim($v['J'])), //公司主体
                    'seller_id'            => PublicInfoService::get_role_id(trim($v['K'])),  //销售员
                    'buyer_id'             => PublicInfoService::get_role_id(trim($v['L'])),  //采购员
                    'claim_arrive_time'    => date('Y-m-d',strtotime(trim($v['M']))),         //要求到货时间
                    'remark'               => trim($v['N']),
                    'status'               => 10,
                    'create_time'          => $this->time,
                    'prepare_needs_id'     => $needs_id,
                    'batch_code'           => $batch_code,
                );
                $datas[] = $data;
            }
        }
        return $datas;
    }

    /**
     * @param $datas
     * @return array
     * 检查导入的备货需求通过分解后的数据
     * khq 2017.1.11
     */
    public function check_upload_resolve_data(&$datas)
    {
        $flag = true;
        $str  = '';
        foreach ($datas as $k=>$v){
            if($v['account_id']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 账号 不存在,导入失败</br>';
            }
            if($v['site_id']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 站点 不存在,导入失败</br>';
            }
            if($v['enterprise_dominant']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 公司主体 不存在,导入失败</br>';
            }
            if($v['seller_id']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 销售员 不存在,导入失败</br>';
            }
            if($v['buyer_id']==''){
                $flag = false;
                $str .= '第'.($k+2).'行 采购员 不存在,导入失败</br>';
            }
        }
        foreach ($datas as $k1=>$v1){                                    //sku+账号+站点+是否退税+到货日期 5维度不能完全一样
            foreach ($datas as $k2=>$v2){
                if($k1>=$k2) continue;
                if($v1['sku']==$v2['sku']){
                    if($v1['account_id']==$v2['account_id'] && $v1['site_id']==$v2['site_id']
                        && $v1['export_tax_rebate']===$v2['export_tax_rebate']
                        && $v1['claim_arrive_time']==$v2['claim_arrive_time']){
                        $flag = false;
                        $str .= '第'.($k1+2).'行与第'.($k2+2).'行信息一致,请不要重复导入</br>';
                    }
                }
            }
        }
        return array(
            'flag'     => $flag,
            'message'  => $str
        );
    }

    /**
     * @param $datas
     * 检查导入的备货需求数据合法性
     * khq 2017.1.11
     */
    public function check_upload_data(&$datas)
    {
        $flag = true;
        $str  = '';
        foreach ($datas as $k=>$v){
            if($k==1) continue;
            if($v['A']==''){
                $flag = false;
                $str .= '第'.$k.'行 SKU 为空,导入失败</br>';
            }
            if($v['B']==''){
                $flag = false;
                $str .= '第'.$k.'行 账号 为空,导入失败</br>';
            }
            if($v['C']==''){
                $flag = false;
                $str .= '第'.$k.'行 站点 为空,导入失败</br>';
            }
            if($v['D']==''){
                $flag = false;
                $str .= '第'.$k.'行 虚拟SKU 为空,导入失败</br>';
            }
            if($v['E']==''){
                $flag = false;
                $str .= '第'.$k.'行 产品名称 为空,导入失败</br>';
            }
            if($v['F']==''){
                $flag = false;
                $str .= '第'.$k.'行 需求数量 为空,导入失败</br>';
            }
            if($v['I']==''){
                $flag = false;
                $str .= '第'.$k.'行 是否退税 为空,导入失败</br>';
            }
            if($v['J']==''){
                $flag = false;
                $str .= '第'.$k.'行 公司主体 为空,导入失败</br>';
            }
            if($v['K']==''){
                $flag = false;
                $str .= '第'.$k.'行 销售员 为空,导入失败</br>';
            }
            if($v['L']==''){
                $flag = false;
                $str .= '第'.$k.'行 采购员 为空,导入失败</br>';
            }
            if($v['M']==''){
                $flag = false;
                $str .= '第'.$k.'行 要求到货日期 为空,导入失败</br>';
            }elseif (!$this->check_date_isValid(trim($v['M']))){
                $flag = false;
                $str .= '第'.$k.'行 要求到货日期 格式不正确,导入失败</br>';
            }elseif (((strtotime($v['M']) - strtotime(date("Y-m-d"))) / 86400 ) < 3 ) {
                $flag = false;
                $str .= '第'.$k.'行 要求到货日期与今天间隔小于3天,导入失败</br>';
            }
        }
        return array(
            'status' => $flag,
            'message'=> $str
        );
    }
    /**
     * 校验日期格式是否正确
     *
     * @param string $date 日期
     * @param string $formats 需要检验的格式数组
     * @return boolean
     * khq 2017.1.11
     */
    function check_date_isValid($date, $formats = array("Y-m-d", "Y/m/d"))
    {
        $unixTime = strtotime($date);
        if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
            return false;
        }

        //校验日期的有效性，只要满足其中一个格式就OK
        foreach ($formats as $format) {
            if (date($format, $unixTime) == $date) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param $datas
     * @return array
     * 检查仓库导入的预捡数量和储位数据合法性
     */
    public function check_create_storage_data(&$datas)
    {
        $flag = true;
        $str  = '';
        foreach ($datas as $k=>$v){
            if($k==1) continue;
            if($v['A']==''){
                $flag = false;
                $str .= '第'.$k.'行 备货需求批次号 为空,导入失败</br>';
            }
            if($v['B']==''){
                $flag = false;
                $str .= '第'.$k.'行 SKU 为空,导入失败</br>';
            }
            if($v['C']==''){
                $flag = false;
                $str .= '第'.$k.'行 账号 为空,导入失败</br>';
            }
            if($v['D']==''){
                $flag = false;
                $str .= '第'.$k.'行 站点 为空,导入失败</br>';
            }
            if($v['H']==''){
                $flag = false;
                $str .= '第'.$k.'行 储位 为空,导入失败</br>';
            }
            if($v['I']!==0.0 &&$v['I']==''){
                $flag = false;
                $str .= '第'.$k.'行 预拣数量 为空,导入失败</br>';
            }
            if($v['J']==''){
                $flag = false;
                $str .= '第'.$k.'行 是否退税 为空,导入失败</br>';
            }
            if (!$this->check_date_isValid(trim($v['M']))){
                $flag = false;
                $str .= '第'.$k.'行 要求到货日期 格式不正确,导入失败</br>';
            }
        }
        return array(
            'status' => $flag,
            'message'=> $str
        );
    }
    /**
     * @return string 批次号
     * 生成批次号 P+年月日+流水号(2位)
     * khq 2016.12.30
     */
    public function create_batch_code()
    {
        $last_code = $this->prepareneeds->get_batch_code();
        if(!$last_code) return false;
        if(substr($last_code, 1,8)==date('Ymd',time()))
        {
            $number = intval(substr($last_code, -2))+1;
            return 'P'.date('Ymd',time()).sprintf("%02d", $number);
        }else{
            return 'P'.date('Ymd',time()).'01';
        }
    }

    /**
     * @param $arr -更新之前的状态
     * @return int
     * 备货需求明细核对
     * khq 2017.1.9
     */
    public function update_status($arr)
    {
        /*$main_flag = $this->prepareneedsdetail->check_prepare_status(                   //检查备货需求主表是否符合当前审核条件
            rtrim($arr['ids'],','),$arr['status']);                                    //上一个阶段未审核完成,则无法进入当前审核
        if($main_flag){
            return 401;
        }*/
        $data = $this->prepareneedsdetail->get_prepare_details_status(
            rtrim($arr['ids'],','),$arr['status']);                                     //判断选中的是否存在状态为非核对的明细
        if($data){
            return 402;
        }else{                                                                          //全部为待核对状态
            $ids_arr = explode(',',$_GET['ids']);
            try{
                $status_to = '';
                switch ($arr['status']){
                    case 10:
                        $status_to = 15;
                        $detail_to = array(
                            'status'               => $status_to,                        //更新状态
                            'seller_check_user_id' => $_SESSION['current_account']['id'],//销售确认人
                            'seller_check_time'    => $this->time                        //销售确认时间
                        );
                        break;
                    case 20:
                        $data = $this->prepareneedsdetail->get_prepare_details(rtrim($arr['ids'],','));
                        foreach ($data as $k=>$v){                                      //判断数量和储位是否未导入
                            if($v['storage']=='' || $v['actual_quanlity']===''){
                                return 403;
                            }
                        }
                        $status_to = 30;
                        $detail_to = array(
                            'status'                => $status_to,
                            'stocker_check_user_id' => $_SESSION['current_account']['id'],
                            'stocker_check_time'    => $this->time
                        );
                        break;
                    /*case 30:
                        $status_to = 50;
                        $detail_to = array(
                            'status'                 => $status_to,
                            'carrier_choose_user_id' => $_SESSION['current_account']['id'],
                            'carrier_choose_time'    => $this->time,
                            'carrier_service_id'     => $_GET['carrier_service_id']
                        );
                        break;*/
                    case 30:
                        $status_to = 80;
                        $detail_to = array(
                            'status'                 => $status_to,
                            'over_user_id'           => $_SESSION['current_account']['id'],
                            'over_time'              => $this->time
                        );
                        break;
                    default:
                        return 405;
                }
                $ids = '';
                foreach ($ids_arr as $k=>$v){
                    $ids .= $v.',';
                    $map = array(
                        'id'     => $v,
                        'status' => array('eq',$arr['status'])
                    );
                    $id = $this->prepareneedsdetail->update($map,$detail_to);             //1.更新备货需求明细状态
                    //$detail_data   = $this->prepareneedsdetail->get_data_by_id($v);

                    //$detail_status = $this->prepareneedsdetail->get_status_by_code(       //2.查出该备货需求的所有明细状态
                    //    rtrim($ids,','),$detail_data[0]['batch_code']);                   //已经更新的明细(id是ids这些明细)除外
                    //$str = '';
                    //foreach ($detail_status as $k){
                    //    $str .=$k['status'].',';
                    //}
                    //if(!in_array($arr['status'], explode(',', rtrim($str,',')))){         //3.判断该备货需求明细是否全部核对过
                    //    $this->prepareneeds->update(array('batch_code'=>$detail_data[0]['batch_code']),
                    //        array('status'=>$status_to));                                 //4.明细全部核对,更新备货需求单状态
                    //}
                }                                                                         //foreach end
                $this->prepareneedsdetail->model->commit();
                return 200;
            }catch (Exception $e){
                $this->prepareneedsdetail->model->rollback();
                print $e->getMessage();
                return 406;
            }
        }
    }

    /**
     * @return int
     * 取消明细
     * khq 2017.1.13
     */
    public function cancel()
    {
        try{
            $map = array(
                'id'     => $_GET['id'],
                'status' => array('neq',80)
            );
            $this->prepareneedsdetail->update(
                $map, array(
                    'status' => 100,
                    'over_user_id' => $_SESSION['current_account']['id'],
                    'over_time' => $this->time
            ));                 //1.更新备货需求明细状态
            /*$detail_data   = $this->prepareneedsdetail->get_data_by_id($_GET['id']);

            $detail_status = $this->prepareneedsdetail->get_status_by_code(               //2.查出该备货需求的所有明细状态
                $_GET['id'],$detail_data[0]['batch_code']);                               //已经更新的明细(id是ids这些明细)除外
            $str = '';
            foreach ($detail_status as $k){
                $str .=$k['status'].',';
            }
            $status_arr = array_unique(explode(',', rtrim($str,',')));
            if(count($status_arr)==1 && $status_arr[0]==100){                             //3.判断该备货需求明细是否全部为取消
                $this->prepareneeds->update(array('batch_code'=>$detail_data[0]['batch_code']),
                    array('status'=>100));                                                //4.明细全部取消,更新备货需求单取消
            }*/
            $this->prepareneedsdetail->model->commit();
            return 100;
        }catch (Exception $e){
            $this->prepareneedsdetail->model->rollback();
            print $e->getMessage();
            return 50;
        }
    }

    public function batch_cancel() {
        try{
            $map = array(
                'id'     => array('IN',$_GET['ids']),
                'status' => array('neq',80)
            );
            $this->prepareneedsdetail->update(
                $map, array(
                'status' => 100,
                'over_user_id' => $_SESSION['current_account']['id'],
                'over_time' => $this->time
            ));
            $this->prepareneedsdetail->model->commit();
            return 100;
        }catch (Exception $e){
            $this->prepareneedsdetail->model->rollback();
            print $e->getMessage();
            return 50;
        }
    }

    /**
     * @return int
     * 检验创建平台计划的数据
     * khq
     */
    public function check_create_fba_data(){
        $datas = $this->prepareneedsdetail->get_prepare_details(rtrim($_GET['ids'],','));
        //$str = '';
        $status_str = '';
        $account_str= '';
        $site_str   = '';
        $carrier_service_id= '';
        foreach ($datas as $k=>$v){
            //$str .= $v['batch_code'].',';
            $status_str .= $v['status'].',';
            $account_str.= $v['account_id'].',';
            $site_str   .= $v['site_id'].',';
            $carrier_service_id .= $v['carrier_service_id'].',';
        }
        //$batch_code_arr = explode(',',rtrim($str,','));
        //$batch_code_arr =array_unique($batch_code_arr);
        //if(count($batch_code_arr)==1){                                                    //同一个备货计划
            $status_arr = array_unique(explode(',',rtrim($status_str,',')));
            if(in_array(100, $status_arr)){                                               //存在取消的明细
                return 402;
            }
            $account_arr = array_unique(explode(',',rtrim($account_str,',')));
            if(count($account_arr)!=1){                                                   //存在多个账号的明细
                return 404;
            }
            $site_arr = array_unique(explode(',',rtrim($site_str,',')));                  //存在多个不同站点明细
            if(count($site_arr)!=1){
                return 405;
            }
            if(in_array(80,$status_arr)){                                                 //存在创建过平台计划单的明细
                return 406;
            }
            $carrier_service_id 
                = array_unique(explode(',',rtrim($carrier_service_id,',')));              //存在不同的物流渠道
            if(count($carrier_service_id)!=1){
                return 408;
            }
            if(count($status_arr)==1){
                if($status_arr[0] != 30){                                                   //状态未审核完成
                    return 403;
                }
                return 200;
            }else{
                return 403;
            }
        //}else{
        //    return 401;                                                                   //有多个备货计划单的明细
        //}
    }

    /**
     * 创建FBA平台计划单
     * khq 2017.1.10
     * 接口数据格式:
        $account_id = 19;
        $options = array(
            'ShipFromAddress' => array(
                'Name'=>'Bpro-ES',
                'AddressLine1'=>'6F , Bonded Warehouse',
                'AddressLine2'=>'Pingan Blv No.1 China South Road , Pinghu Town',
                'City'=>'Shenzhen',
                'StateOrProvinceCode'=>'Guangdong',
                'PostalCode'=>'518000',
                'CountryCode'=>'CN',
            ),
            'LabelPrepPreference' => 'SELLER_LABEL',
            'shipmentPlanItems' => array(
                array(
                    'SellerSKU'=>'AF_AM54302',
                    'Quantity' => '10',
                ),
                array(
                    'SellerSKU'=>'AF_AM84800',
                    'Quantity' => '10',
                ),
            ),
        )
        返回数据格式:
            $arr = array(
                0 => array(
                    'ShipmentId' => 'FBAZ7WZYY',
                    'DestinationFulfillmentCenterId' => 'LTN4',
                    'ship_to_address_id' => 14,
                    'ship_from_address_id' => 1,
                    'Items' => array(
                        0 => array(
                            'SellerSKU' => 'GYSAM55702',
                            'FulfillmentNetworkSKU' => 'X000LEBX4Z',
                            'Quantity' => 50,
                        ),
                        1 => array(
                            'SellerSKU' => 'GYSAM55701',
                            'FulfillmentNetworkSKU' => 'X000LDOIM5',
                            'Quantity' => 80
                        )
                    )
                )
            );
     */
    public function create_fba_stocking_plan()
    {
        $datas    = $this->prepareneedsdetail->get_prepare_details(rtrim($_GET['ids'],','));
        $min_date = 
            $this->prepareneedsdetail->get_min_date(rtrim($_GET['ids'],','));      //最近的到货日期
        $account_id = $datas[0]['account_id'];
        if($account_id=='') return array('status' => 402);
        $options = array(
            'LabelPrepPreference' => 'SELLER_LABEL',                               //打印条码
        );
        $seller_sku_skus = D('Api/Amazon/AccountSellerSku','Service')
            ->getActualSkuByAccountIdAndSellerSku($account_id);                    //获取平台sku-内部sku k-v键值数组
        $sku_seller_skus = array_flip($seller_sku_skus);
        foreach ($datas as $k=>$v){
            $seller_skus = $v['seller_sku'] ? $v['seller_sku'] : $sku_seller_skus[$v['sku']];
            $options['shipmentPlanItems'][]= array(
                'SellerSKU'=> $seller_skus,
                'Quantity' => $v['needs_quantity']
            );
            if($seller_skus=='') return array('status' => 403,'message'=>$v['sku']);
            if ($v['needs_quantity'] <= 0) return array('status' => 404,'message'=>$v['sku']);
            $title = PublicInfoService::get_title_by_sellersku($account_id, $seller_skus);
            if($title=='') return array('status' => 406,'message'=>$v['sku']);        //title是否存在
            //if($v['site_id']==107) return array('status' => 407,'message'=>$v['sku']);//美国站点,不能创建平台就计划单
        }
        try{
            $fba_data = D('Api/Amazon/Inbound','Service')->createInboundShipmentPlan($account_id,$options);//平台接口
            if($fba_data['status']==500){
                return array('status' => 405,'message'=>$fba_data['msg']);die;
            }
            $this->update_status(array('ids' => $_GET['ids'], 'status' => 30));            //更新状态
            $shipment_public_data = array(                                            //公共的数据
                'account_id' => $datas[0]['account_id'],
                'account_name' => $datas[0]['account_name'],
                'site_id' => $datas[0]['site_id'],
                //'batch_code' => $datas[0]['batch_code'],
                //'carrier_service_id' => $datas[0]['carrier_service_id'],
                'claim_arrive_time' => $min_date,
                'create_user_id' => $_SESSION['current_account']['id'],
                'create_time' => $this->time,
            );
            $shipment_ids = '';
            foreach ($fba_data['msg'] as $k=>$v){                                            //亚马逊平台返回数据
                $shipment_ids .= $v['ShipmentId'].' ';
                $shipment_data['shipmentid'] = $v['ShipmentId'];                      //小花主表的数据 平台计划单
                $shipment_data['shipment_name'] = $v['ShipmentName'];                      //小花主表的数据 平台计划单
                $shipment_data['destination_fullfillment_center_id'] = $v['DestinationFulfillmentCenterId'];
                $shipment_data['ship_to_address_id']   = $v['ship_to_address_id'];    //目的地id
                $shipment_data['ship_from_address_id'] = $v['ship_from_address_id'];  //起运地id
                $shipment_data = array_merge($shipment_data,$shipment_public_data);

                foreach ($v['Items'] as $ik=>$iv){                                    //返回数据的明细
                    foreach ($datas as $dk=>$dv){                                     //选择创建fba平台计划的明细
                        if($seller_sku_skus[$iv['SellerSKU']]==$dv['sku']){           //两者通过sku对应
                            $need_arr = array(
                                'prepare_needs_details_id' => $dv['id'],
                                'shipmentid'               => $v['ShipmentId'],
                                'plan_num'                 => $iv['Quantity'],
                                'status'                   => 10
                            );
                            $this->insert_prepare_needs_details_shipmentid($need_arr);//创建备货需求明细平台计划单关联表
                            $shipment_data['detail'][$ik]=array(                      //小花明细的数据 平台计划单明细
                                'sku'        => $dv['sku'],                           //公司sku
                                'seller_sku' => $iv['SellerSKU'],                     //平台sku
                                'sku_name'   => $dv['sku_name'],
                                //'sku_virtual'=> $dv['sku_virtual'],
                                'fnsku'      => $iv['FulfillmentNetworkSKU'],
                                //'position'   => $dv['storage'],
                                'quantity'   => $iv['Quantity'],
                                'hs_code'    => $dv['hs_code'],
                                'sku_cname'  => $dv['sku_cname'],
                                'export_tax_rebate'   => $dv['export_tax_rebate'],
                                'enterprise_dominant' => $dv['enterprise_dominant'],
                                'declaration_element' => $dv['declaration_element'],
                                'remark' => $_GET['remark']
                            );
                        }
                    }
                }
                D('Inboundshipmentplan','Service')->create($shipment_data);
                unset($shipment_data);
            }
            return array(
                'status' => 200,
                'message'=> $shipment_ids
            );
        }catch (Exception $e){
            return array(
                'status' => 401,
                'message'=> ''
            );
        }
        
    }

    /**
     * @param $_arr
     * 创建备货需求明细平台计划单关联表
     * khq 2017.1.10
     */
    public function insert_prepare_needs_details_shipmentid(&$_arr)
    {
        $data = array(
            'prepare_needs_details_id' =>
                !empty($_arr['prepare_needs_details_id'])?$_arr['prepare_needs_details_id']:'',
            'shipmentid'               => $_arr['shipmentid'],
            'plan_num'                 => $_arr['plan_num'],
            'status'                   => 10,
            'create_time'              => $this->time
        );
        $this->prepareneedsdetailsshipmentid->create($data);
    }

    /**
     * @return int 10当前状态不可编辑 100更新成功 20更新失败
     * 编辑单个明细信息
     * khq 2017.1.13
     */
    public function ajax_edit()
    {
//        print_r($_GET);
//        exit;
        $detail_data = $this->ajax_select_detail(array('id'=>$_GET['id']));
        $data = array();
        switch ($detail_data['status'])
        {
            case 10:                                                             //待销售确认
                $data = array(
                    'needs_quantity'    => $_GET['needs_quantity'],
                    'export_tax_rebate' => $_GET['export_tax_rebate'],
                    'sku_name' => $_GET['sku_name'],
                    'remark' => $_GET['remark'],
                    'cargo_grade' => $_GET['cargo_grade']
                );
                break;
            case 20:                                                             //待仓库确认
                $data = array(
                    /*'storage'         => $_GET['storage'],
                    'actual_quanlity' => $_GET['actual_quanlity']*/
                    'remark' => $_GET['remark'],
                    'cargo_grade' => $_GET['cargo_grade']
                );
                break;
            case 30:                                                             //待物流确认
                $data = array(
                    /*'carrier_service_id'         => $_GET['carrier_service_id']*/
                    'needs_quantity'    => $_GET['needs_quantity'],
                    'remark' => $_GET['remark'],
                    'cargo_grade' => $_GET['cargo_grade']
                );
                break;
            default:
                return 401;
        }      
        try{
            $exists=PublicInfoService::getOverseasSupervision($_GET['sku'],$_GET['site']);
            $skuObject = M('sku_site_relation','fba_','fbawarehouse');
            if(empty($exists)){
                $dataSku=array(
                    'sku'=>$_GET['sku'],
                    'site_id'=>$_GET['site'],
                    'overseas_supervision'=>$_GET['overseas_supervision'],
                    'cargo_grade'=>$_GET['cargo_grade'],
                    'create_time'=>time(),
                );
                $result1=$skuObject->data($dataSku)->add();
            }else{
                $dataSku=array(
                    'overseas_supervision'=>$_GET['overseas_supervision'],
                    'cargo_grade'=>$_GET['cargo_grade'],
                    'update_time'=>time()
                );
                $result1=$skuObject->where("sku='".$_GET['sku']."' and site_id=".$_GET['site'])->save($dataSku);
            }
            $result2=$this->prepareneedsdetail->update(array('id'=>$_GET['id']),$data);
            $this->prepareneedsdetail->model->commit();
            
            return 200;
        }catch (Exception $e){
            $this->prepareneedsdetail->model->rollback();
            print $e->getMessage();
            return 402;
        }
    }
    /**
     * 检查批次里面所有需求是否全部已完成或取消,改变批次状态
     * kelvin 2017-03-07
     */
    public function updateBateCodeStatus($batch_code)
    {
        if ($batch_code) {
            $result = $this->prepareneedsdetail->checkBateCodeAllStatus($batch_code);
            if (count($result) == 0) {
                M('prepare_needs', 'fba_', 'DB_FBAERP')->where("batch_code = '$batch_code'")->setField('status', 80);
            }
        }
    }
    /**
     * 描述: 数据分页,将查出来的数据进行分页
     * 作者: kelvin
     */
    public function ownPage($page = 1,$size = 20,$data) {
        $result = array();
        $num = 0;
        foreach ($data as $k =>$v){
            if($num<($page*$size) && $num>=($page-1)*$size){
                $num +=1;
                $result[] = $v;
            }else{
                $num +=1;
                continue;
            }

        }
        return $result;
    }
    /**
     * 描述:导出
     * 作者:kelvin
     */
    public function downPcSearch($data)
    {

        if(count($data)>0){
            set_time_limit(0);
            ini_set('memory_limit','2048M');

            $output = fopen('php://output', 'w') or die("can't open php://output");
            header("Content-Type: application/csv");
            header("Content-Disposition: attachment; filename=PC单号导出.(" .date("Ymd").").csv");
            ob_end_clean();
            $firstLine = array(
                'pc_id' =>'PC单号',
                'sku' =>'sku',
                'end_status' =>'状态',
                'shipmentid' =>'shipmentid',
                'site_id' =>'站点',
                'account_name' =>'账号',
                'asin' =>'ASIN',
                'seller_sku' =>'SellerSku',
                'sku_name' =>'中文名称',
                'create_time' =>'备货创建时间',
                'export_tax_rebate' =>'是否退税',
                'enterprise_dominant' =>'公司主体',
                'needs_quantity' =>'需求数量',
                'claim_arrive_time' =>'要求到货时间',
                'seller_check_time' =>'销售确认时间',
                'compliance_check_time' =>'合规审核时间',
                'logistic_check_time' =>'物流预审时间',
                'over_time' =>'备货取消时间',
                'plan_create_time' =>'生成计划单时间',
                'push_warehouse_time' =>'推送仓库时间',
                'picking_time' =>'拣货确认时间',
                'box_create_time' =>'录入箱唛数据时间',
                'package_upload_time' =>'装箱确认时间',
//                'pc_id' =>'平台计划取消时间',
                'tran_create_time' =>'生成物流计划时间',
                'pickup_op_time' =>'物流发货时间',
                'create_user_id' =>'需求创建人',
            );
            fputcsv($output, array_values($firstLine));
            foreach ($data as $_data) {
                $_output = array();
                foreach ($firstLine as $key => $val) {
                    $_output[$key] = $_data[$key];
                }
                fputcsv($output, array_values($_output));
            }

            fclose($output) or die("can't close php://output");
            exit;
        }else{
            echo "<script>alert('数据为空');history.go(-1)</script>";die;
        }
    }
    /**
     * 描述:根据账号sellersku查找asin
     * 作者:kelvin
     */
    public function format($data){
        $skus = str_replace(array("\r\n", "\r", "\n"),";",$data);  //处理换行
        $skus = str_replace(" ",";",$skus);  //处理换行
        $skus = str_replace(";",",",$skus);  //处理换行
        $skus = str_replace("，",",",$skus);  //处理中文逗号
        $skus = rtrim($skus,",");
        $skus = array_filter(explode(",",$skus));
        $skus = array('in',$skus);
        return $skus;
    }
}